<?php
/**
 * Created by PhpStorm.
 * User: papa
 * Date: 18/5/10
 * Time: 11:43
 */

namespace app\admin\model;


use think\Model;

class BaseModel extends Model
{
    //开启写入时间戳
    protected $autoWriteTimestamp = 'datetime';

    //公共方法，按照时间排序和分页
    public static function getSortData($num)
    {
        return self::order('create_time','desc')->paginate($num,false,[
            'type' => 'page\Page',
        ]);
    }

    /*
     * 公共搜索方法，返回where条件
     * $data中三个字段，参考订单和当面付的例子及注释
     */
    public static function getSearch($data = null)
    {
        //分页参数会导致where条件搜索报错，在这里销毁
        if(!empty($data['page'])) unset($data['page']);
        //如果$data不为空
        $where = array();
        if (!empty($data)) {
            foreach ($data as $key=>$value) {
                //字段值查询
                if($key == 'value'){
                    foreach($value as $k=>$v){
                        if(!empty($v)){
                            $where[$k] = $v;
                        }
                    }
                }

                //模糊查询
                if($key == 'like'){
                    foreach($value as $k=>$v){
                        if(!empty($v)){
                            $where[$k] = ['like','%'.$v.'%'];
                        }
                    }
                }
                //模糊查询
                if($key == 'time'){
                    //时间查询，两个值都不能为空
                    if(!empty($value['start_time']) && !empty($value['end_time'])){
                        $where['create_time'] = ['between time',[$value['start_time'].' 00:00:00',$value['end_time'].' 23:59:59']];
                    }
                    //查询开始时间为空，结束时间不为空
                    if(empty($value['start_time']) && !empty($value['end_time'])){
                        $where['create_time'] = ['<= time',$value['end_time'].' 23:59:59'];
                    }
                }
            }
        }
        return $where;
    }
}